package club.hicode.daydayup.netty.udp.client;

import club.hicode.daydayup.netty.udp.MessageBo;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.json.JSONUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.socket.DatagramPacket;

import java.net.InetSocketAddress;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Req的抽象实现。
 * todo 此处是否应该作为抽象了？
 *
 * @author Liu Chunfu
 * @date 2018-07-09 下午4:28
 **/
public class AbstractReq implements IReq {

    @Override
    public MessageBo req(MessageBo message) {
        Channel channel = UdpClient.CHANNEL;

        //对方的ip地址
        InetSocketAddress remoteAddress = new InetSocketAddress("127.0.0.1", 9876);
        //内容
        String heart = JSONUtil.toJsonStr(message) + "$";
        ByteBuf bytebuf = Unpooled.copiedBuffer(heart, CharsetUtil.CHARSET_UTF_8);
        //发送
        DatagramPacket datagramPacket = new DatagramPacket(bytebuf, remoteAddress);
        channel.writeAndFlush(datagramPacket);
        String id = message.getId();
        System.out.println("发送:" + message);

        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        try {
            KV.put(id, lock, condition);
            lock.lock();
            condition.await();
            MessageBo messageBo = AgentHandler.map.get(id);
            return messageBo;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(123);
        }
        return null;
    }
}
